/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include <string.h>
#include <openjpeg.h>

#include "Xern/IResource.hpp"
#include "Xern/IResourceLoader.hpp"
#include "Xern/IRenderer.hpp"

#include "Xern/DataFilter.hpp"
#include "Xern/DataTypes.hpp"
#include "Xern/Engine.hpp"
#include "Xern/Exceptions.hpp"
#include "Xern/FileSystem.hpp"
#include "Xern/Log.hpp"
#include "Xern/PluginFactory.hpp"

namespace XernOpenJpeg
{
	using namespace Xern;

	class OpenJpegLoader: public IResourceLoader
	{
	public:
		OpenJpegLoader();
		~OpenJpegLoader();

		virtual bool CanLoadResource(const std::string &filename, const std::string &group) const;
		virtual bool CanLoadResource(const std::string &mime) const;

		virtual boost::shared_ptr<IResource>
		LoadResource(const std::string &filename, const std::string &group, const std::string &path) const;
		virtual boost::shared_ptr<IResource>
		LoadResource(const std::string &mime, boost::shared_ptr<IDataFilter> data) const;

		mutable opj_dparameters_t parameters;
	};

	static Xern::PluginFactory<OpenJpegLoader> loaderFactory("ResourceLoader", "OpenJpeg");

	OpenJpegLoader::OpenJpegLoader()
	{
	}

	OpenJpegLoader::~OpenJpegLoader()
	{
	}

	bool OpenJpegLoader::CanLoadResource(const std::string &filename, const std::string &group) const
	{
		std::string ext = FileExtension(filename);
		if(ext == ".j2c" || ext == ".jp2")
			return true;
		return false;
	}

	bool OpenJpegLoader::CanLoadResource(const std::string &mime) const
	{
		if(mime == "image/jp2" || mime == "image/x-j2c")
			return true;
		return false;
	}

	boost::shared_ptr<IResource>
	OpenJpegLoader::LoadResource(const std::string &filename, const std::string &group, const std::string &path) const
	{
		// Sanity check.
		assert(CanLoadResource(filename, group));

		// Open the file.
		FILE *in = fopen(path.c_str(), "rb");

		// Create the filter.
		boost::shared_ptr<IDataFilter> filter(new FileFilter(in, true));

		// Load the image.
		std::string ext = FileExtension(filename);
		if(ext == ".j2c")
		{
			return LoadResource("image/x-j2c", filter);
		}
		else if(ext == ".jp2")
		{
			return LoadResource("image/jp2", filter);
		}
		else
		{
			assert(NULL);
			return boost::shared_ptr<IResource> ();
		}
	}

	static void ErrorCallback(const char *msg, void *client_data)
	{
		std::string m = msg;
		if(m.size() > 0 && m[m.size()-1] == '\n')
			m[m.size()-1] = 0;

		LogConsole->Error("%s", m.c_str());
	}

	static void WarningCallback(const char *msg, void *client_data)
	{
		std::string m = msg;
		if(m.size() > 0 && m[m.size()-1] == '\n')
			m[m.size()-1] = 0;

		LogConsole->Warning("%s", m.c_str());
	}

	static void InfoCallback(const char *msg, void *client_data)
	{
		std::string m = msg;
		if(m.size() > 0 && m[m.size()-1] == '\n')
			m[m.size()-1] = 0;

		LogConsole->Notify("%s", m.c_str());
	}

	boost::shared_ptr<IResource>
	OpenJpegLoader::LoadResource(const std::string &mime, boost::shared_ptr<IDataFilter> filter) const
	{
		// Sanity check.
		assert(CanLoadResource(mime));

		// Configure the event manager.
		opj_event_mgr_t eventMan;
		memset(&eventMan, 0, sizeof(eventMan));
		eventMan.error_handler = ErrorCallback;
		eventMan.warning_handler = WarningCallback;
		eventMan.info_handler = InfoCallback;

		// Read the input file.
		filter->Seek(0, IDataFilter::ST_END);
		size_t sourceLen = filter->GetPosition();
		filter->Seek(0, IDataFilter::ST_SET);
		u8 *source = new u8[sourceLen];
		filter->Read(sourceLen, source);

		// Use default decoding parameters.
		opj_set_default_decoder_parameters(&parameters);

		// Create the decompressor.
		opj_dinfo_t *codec;
		opj_image_t *image;
		if(mime == "image/x-j2c")
		{
			codec = opj_create_decompress(CODEC_J2K);
			parameters.decod_format = CODEC_J2K;
		}
		else if(mime == "image/jp2")
		{
			codec = opj_create_decompress(CODEC_JP2);
			parameters.decod_format = CODEC_JP2;
		}
		else
		{
			assert(NULL);
			return boost::shared_ptr<IResource> ();
		}

		// Catch events.
		opj_set_event_mgr((opj_common_ptr)codec, &eventMan, NULL);

		// Setup the decoder.
		opj_setup_decoder(codec, &parameters);

		// Open a byte stream.
		opj_cio_t *stream = opj_cio_open((opj_common_ptr)codec, source, sourceLen);

		// Decode the stream.
		image = opj_decode(codec, stream);
		if(!image)
		{
			delete [] source;
			opj_destroy_decompress(codec);
			opj_cio_close(stream);
			throw XernException("Failed to decode Jpeg 2000 image.");
		}

		// Close the byte stream.
		opj_cio_close(stream);

		// Delete the source.
		delete [] source;
		source = NULL;

		// Read the image data.
		int width = image->comps[0].w;
		int height = image->comps[0].h;
		int numchannels = image->numcomps;
		int bpp = numchannels*8;
		float scale[4];
		for(int i = 0; i < numchannels; i++)
			scale[i] = 255.0f / (float)((1<<image->comps[i].prec)-1);

		ITexture::TextureFormat format;
		switch(bpp)
		{
		case 8:
			format = ITexture::TF_L8;
			break;
		case 16:
			format = ITexture::TF_LA8;
			break;
		case 24:
			format = ITexture::TF_RGB8;
			break;
		case 32:
			format = ITexture::TF_RGBA8;
			break;
		default:
			assert(NULL);
			break;
		}

		// Create the image buffer.
		size_t bufferSize = width*height*numchannels;
		u8 *buffer = new u8[bufferSize];

		// Encode the pixels.
		size_t numpixels = width*height;

		for(size_t i = 0; i < numpixels; i++)
		{
			switch(numchannels)
			{
			case 1:
				buffer[i] = u8(image->comps[0].data[i]*scale[0]);
				break;
			case 2:
				buffer[i*2] = u8(image->comps[0].data[i]*scale[0]);
				buffer[i*2+1] = u8(image->comps[1].data[i]*scale[1]);
				break;
			case 3:
				buffer[i*3] = u8(image->comps[2].data[i]*scale[2]);
				buffer[i*3+1] = u8(image->comps[1].data[i]*scale[1]);
				buffer[i*3+2] = u8(image->comps[0].data[i]*scale[0]);
				break;
			case 4:
				buffer[i*4] = u8(image->comps[2].data[i]*scale[2]);
				buffer[i*4+1] = u8(image->comps[1].data[i]*scale[1]);
				buffer[i*4+2] = u8(image->comps[0].data[i]*scale[0]);
				buffer[i*4+3] = u8(image->comps[3].data[i]*scale[3]);
				break;
			default:
				assert(NULL);
				break;
			}
		}

		// Create the texture.
		boost::shared_ptr<ITexture> texture = Engine::Get().GetRenderer()->CreateTexture2D(width, height, format, bufferSize, buffer);

		// Delete the buffer.
		delete [] buffer;

		// Destroy the codec and the image.
		opj_destroy_decompress(codec);
		opj_image_destroy(image);

		// Return the texture.
		return texture;
	}

};
